package com.atguigu.yygh.common.exception;

import com.atguigu.yygh.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @ClassName GlobalExceptionHandler
 * @Description 此类描述:
 * @Author dangchen
 * @DateTime 2022-09-29 21:06
 * @Version 1.0
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //1.统一异常处理
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R exception(Exception e){
        e.printStackTrace();
        return R.error();
    }

    //2.特定异常处理   1/2都存在,执行精确匹配的 -- 2
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public R arithmeticException(ArithmeticException e){
        e.printStackTrace();
        return R.error().message("出现了ArithmeticException异常");
    }

   //3.自定义异常处理
    @ExceptionHandler(YyghException.class)
    @ResponseBody
    public R yyghException(YyghException e){
        e.printStackTrace();
        log.error(e.getMsg());
        return R.error().message(e.getMsg()).code(e.getCode());
    }
}